import coloredlogs
import logging
import logging.config
import os
import time
import yaml
# 项目根路径
from utili import ProjectUtil

import configs.config  # 加载配置
import tools.global_variable as glv

path = glv.get("rootpath")

# print("LgoConfigYaml"+"-----------------------"+BASE_DIR+"----------------------")

# 日志配置文件
LOG_CONF_FILE = os.path.join(path, 'configs\logger.yaml')

# print("LgoConfigYaml"+"-----------------------"+LOG_CONF_FILE+"----------------------")


def setup_logging(default_path=LOG_CONF_FILE, default_level=logging.DEBUG, env_key='LOG_CFG'):

    """
    配置项目日志信息
    :param default_path: 日志文件默认路径
    :param default_level: 日志默认等级
    :param env_key: 系统环境变量名
    :return:
    """
    path = default_path

    value = os.getenv(env_key, None)  # 获取对应的环境变量值
    if value is not None:
        path = value

    rootpath = ProjectUtil.ProjectUtil.project_root_path('agent-interface-auto-python')
    # print("LgoConfigYaml"+"-----------------------"+rootpath + "----------------------------------------rootpath")
    errorfilename = rootpath + 'logs\\' + time.strftime('%Y-%m-%d',
                                                        time.localtime(time.time())) + '-error' + '.log'
    serverfilename = rootpath + 'logs\\' + time.strftime('%Y-%m-%d',
                                                         time.localtime(time.time())) + '-server' + '.log'

    # print("LgoConfigYaml"+path+"---------------------------------------path")
    if os.path.exists(path):
        with open(path, mode='r', encoding='utf-8') as f:
            try:
                logging_yaml = yaml.safe_load(f.read())
                logging.config.dictConfig(logging_yaml)
                # print("LgoConfigYaml"+"-----------------------"+logging_yaml['handlers']['error_file_handler']['filename'] )
                # print("LgoConfigYaml"+"-----------------------"+logging_yaml['handlers']['server_file_handler']['filename'])
                logging_yaml['handlers']['error_file_handler']['filename'] = errorfilename
                logging_yaml['handlers']['server_file_handler']['filename'] = serverfilename

                coloredlogs.install(level='DEBUG')
            except Exception as e:
                print(e)
                print('无法加载日志配置文件, 请检查日志目录是否创建, 使用默认的日志配置')
                logging.basicConfig(level=default_level)
                coloredlogs.install(level=default_level)
    else:
        logging.basicConfig(level=default_level)
        coloredlogs.install(level=default_level)
        print('日志配置文件不存在, 使用默认的日志配置')


if __name__ == '__main__':
    setup_logging()
    logger = logging.getLogger('server')
    logger.debug('debug log test1111')
    logger.info('info log test2222')
    logger.warning('warning log test33333')
    logger.error('error log test4444')
